//
//  Team9UserViewController.m
//  Team9Project
//
//  Created by 朱嘉祺 on 15/10/12.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "Team9UserViewController.h"
#import "Team9BaseTableViewCell.h"
#import "Team9EveningType.h"
#import "Team9JQHeader.h"
#import <objc/runtime.h>
#import "Team9SaveViewController.h"

@interface Team9UserViewController ()<UITableViewDataSource, UITableViewDelegate,
UIAlertViewDelegate>

@property(nonatomic, retain) NSArray *array;
@property(nonatomic, retain) UISwitch *eveningType;
@property(nonatomic, retain) UITableView *tableView;


@end

@implementation Team9UserViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array =
        @[ @"版本信息",
           @"我的关注",
           @"夜间模式",
           @"清除缓存" ];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    [self createTableView];
    self.title = @"我的";
}
static NSString *userReuse = @"userReuse";
static NSString *userEveningReuse = @"userEveningReuse";

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame
                                                  style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //    _tableView.rowHeight = 50;
    _tableView.bounces = NO;
    
    UILabel *nameLabel =
    [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50 * WIDTH / 375)];
    nameLabel.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.900];
    nameLabel.font = [UIFont systemFontOfSize:17];
    
    nameLabel.text = @"我的收藏";
    nameLabel.tag = 1000;
    nameLabel.textAlignment = NSTextAlignmentCenter;
    _tableView.tableHeaderView = nameLabel;
    
    UIView *footView = [[Team9BaseView alloc] initWithType:ViewTYpeLight];
    _tableView.tableFooterView = footView;
}


#pragma mark 夜间模式
- (void)changecolor {
    
    UILabel *nameLabel = (UILabel *)[_tableView viewWithTag:1000];
    Team9EveningType *evening = [Team9EveningType shareEvening];
    if ([evening eveningFailling]) {
        [UIView animateWithDuration:0.3
                         animations:^{
                             _tableView.separatorColor = [UIColor whiteColor];
                             nameLabel.backgroundColor = [UIColor colorWithWhite:0.15 alpha:1];
                             [super changecolor];
                              nameLabel.textColor = [UIColor whiteColor];
                             _tableView.backgroundColor = [UIColor colorWithWhite:0.15 alpha:1];
                         }
                         completion:^(BOOL finished) {
                             
                         }];
        
    } else {
        [UIView animateWithDuration:0.3
                         animations:^{
                             _tableView.separatorColor = [UIColor lightGrayColor];
                             nameLabel.textColor = [UIColor blackColor];
                             nameLabel.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
                             [super changecolor];
                             _tableView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
                         }
                         completion:^(BOOL finished) {
                         }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    return _array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row != 2) {
        Team9BaseTableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:userReuse];
        if (!cell) {
            cell = [[Team9BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:userReuse];
        }
        cell.textLabel.text = _array[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    } else if (indexPath.row == 2) {
        Team9BaseTableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:userEveningReuse];
        if (!cell) {
            cell =
            [[Team9BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:userEveningReuse];
            cell.textLabel.text = _array[indexPath.row];
            self.eveningType =
            [[UISwitch alloc] initWithFrame:CGRectMake(WIDTH - 90, 6, 80, 30)];
            _eveningType.layer.cornerRadius = 15;
            _eveningType.layer.masksToBounds = YES;
            [cell.contentView addSubview:_eveningType];
            _eveningType.backgroundColor = [UIColor whiteColor];
            _eveningType.onTintColor = [UIColor grayColor];
            if ([Team9EveningType shareEvening].eveningFailling) {
                [_eveningType setOn:YES];
            } else
                [_eveningType setOn:NO];
            [_eveningType addTarget:self
                             action:@selector(eveningChange:)
                   forControlEvents:UIControlEventValueChanged];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
    
    return nil;
}
- (void)eveningChange:(UISwitch *)evenningType {
    Team9EveningType *evening = [Team9EveningType shareEvening];
    evening.eveningFailling = evenningType.isOn;
    [[NSUserDefaults standardUserDefaults]
     setValue:[NSString stringWithFormat:@"%d", evening.eveningFailling]
     forKey:@"evening"];
//    NSLog(@"%d", evening.eveningFailling);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changecolor"
                                                        object:nil
                                                      userInfo:nil];
}

static void *clearAlertView = "clearAlertView";
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *pathCourse = [NSHomeDirectory()
                            stringByAppendingString:@"/Library/Caches/meilijia/"];
    NSString *message =
    [NSString stringWithFormat:@"缓存大小为\n内容:%.03lgM\n图片:%.03gM\n是否清空",
     [self folderSizeAtPath:pathCourse],
     [[SDImageCache sharedImageCache] getSize] /
     1024.0 / 1024.0];
    if (indexPath.row == 3 && [UIDevice version] <= 8.0) {
        UIAlertView *clear = [[UIAlertView alloc]
                              initWithTitle:@"清除缓存"
                              message:message
                              delegate:self
                              cancelButtonTitle:@"取消"
                              otherButtonTitles:@"清除数据", @"清除图片", nil];
        [clear show];
        clear.tag = 1000;
        void (^block)(NSInteger) = ^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                NSFileManager *manager = [NSFileManager defaultManager];
                [manager removeItemAtPath:pathCourse error:nil];
            }
            if (buttonIndex == 2) {
                // sd 清除缓存(share default)
                [[SDImageCache sharedImageCache] clearDisk];
            };
        };
        objc_setAssociatedObject(clear, clearAlertView, block,
                                 OBJC_ASSOCIATION_COPY);
    } else if (indexPath.row == 3 && [UIDevice version] > 8.0){
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *canceAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction *enterAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSFileManager *manager = [NSFileManager defaultManager];
            [manager removeItemAtPath:pathCourse error:nil];
        }];
        UIAlertAction *allAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[SDImageCache sharedImageCache] clearDisk];
        }];
        [alertVC addAction:canceAction];
        [alertVC addAction:enterAction];
        [alertVC addAction:allAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
    }
    if (indexPath.row == 0) {
        if ([UIDevice version] > 8.0) {
            UIAlertController *alertVC = [UIAlertController
                                          alertControllerWithTitle:@"1.0版"
                                          message:@"createBy@2015,郭小磊,叶婷,朱嘉祺"
                                          preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertVC animated:YES completion:nil];
            dispatch_after(
                           dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
                           dispatch_get_main_queue(), ^{
                               [alertVC dismissViewControllerAnimated:YES
                                                           completion:^{
                                                           }];
                           });
        } else {
            UIAlertView *alert =
            [[UIAlertView alloc] initWithTitle:@"1.0版"
                                       message:@"createBy@2015,郭小磊,叶婷,朱嘉祺"
                                      delegate:self
                             cancelButtonTitle:nil
                             otherButtonTitles:nil, nil];
            [alert show];
            alert.tag = 1001;
            dispatch_after(
                           dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),
                           dispatch_get_main_queue(), ^{
                               [alert dismissWithClickedButtonIndex:0 animated:YES];
                           });
        }

    }
    if (indexPath.row == 1) {
        Team9SaveViewController *saveVc = [Team9SaveViewController new];
        [self.navigationController pushViewController:saveVc animated:YES];
    }
}
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1000) {
        void (^block)(NSInteger) =
        objc_getAssociatedObject(alertView, clearAlertView);
        block(buttonIndex);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (float)folderSizeAtPath:(NSString *)folderPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    NSEnumerator *childFilesEnumerator = [[manager
                                           subpathsAtPath:folderPath] objectEnumerator]; //从前向后枚举器／／／／//
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        //        NSLog(@"fileName ==== %@",fileName);
        NSString *fileAbsolutePath =
        [folderPath stringByAppendingPathComponent:fileName];
        //        NSLog(@"fileAbsolutePath ==== %@",fileAbsolutePath);
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    //    NSLog(@"folderSize ==== %lld",folderSize);
    return folderSize / 1024.0f / 1024.0f;
}
- (long long)fileSizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        
        //        //取得一个目录下得所有文件名
        //        NSArray *files = [manager subpathsAtPath:filePath];
        //        NSLog(@"files1111111%@ == %ld",files,files.count);
        //
        //        // 从路径中获得完整的文件名（带后缀）
        //        NSString *exe = [filePath lastPathComponent];
        //        NSLog(@"exeexe ====%@",exe);
        //
        //        // 获得文件名（不带后缀）
        //        exe = [exe stringByDeletingPathExtension];
        //
        //        // 获得文件名（不带后缀）
        //        NSString *exestr = [[files objectAtIndex:1]
        //        stringByDeletingPathExtension];
        //        NSLog(@"files2222222%@  ==== %@",[files objectAtIndex:1],exestr);
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
    return 0;
}

@end
